package com.briup.pts.utils;

import jakarta.servlet.http.HttpServletRequest;

import java.util.regex.Pattern;

public class IpUtil {
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    public static String getRealIp(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_CLIENT_IP",
                "HTTP_CLIENT_IP"
        };

        for (String header : headers) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                String[] ips = ipList.split(",");
                for (String ip : ips) {
                    if (isValidIPv4(ip.trim())) {
                        return ip.trim();
                    }
                }
            }
        }

        String remoteAddr = request.getRemoteAddr();
        if (isValidIPv4(remoteAddr)) {
            return remoteAddr;
        }

        return "127.0.0.1";
    }

    private static boolean isValidIPv4(String ip) {
        return IPV4_PATTERN.matcher(ip).matches();
    }
}
